package com.junjie.blibli.service.impl;

import com.junjie.blibli.Constant.AuthRoleConstant;
import com.junjie.blibli.Entity.auth.*;
import com.junjie.blibli.service.AuthRoleService;
import com.junjie.blibli.service.UserAuthService;
import com.junjie.blibli.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class UserAuthServiceImpl implements UserAuthService {
    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private AuthRoleService authRoleService;

    @Override
    public UserAuthorities getUserAuthorities(Long userId) {
        //先获取当前用户的所有角色
        List<UserRole> userRoles = userRoleService.getUserRoleByUserId(userId);
        //将角色id提取出来
        Set<Long> roleIdSet = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toSet());
        //查操作权限
        List<AuthRoleElementOperation> roleElementOperationList = authRoleService.getRoleElementOperationByRoleIds(roleIdSet);
        //查菜单权限
        List<AuthRoleMenu> authRoleMenuList = authRoleService.getRoleMenuesByRoleIds(roleIdSet);
        //属性给到UserAuthorities，并返回
        UserAuthorities userAuthorities = new UserAuthorities();
        userAuthorities.setRoleElementOperationList(roleElementOperationList);
        userAuthorities.setRoleMenuList(authRoleMenuList);
        return userAuthorities;
    }

    @Override
    public void addUserDefaultRole(Long id) {
        UserRole userRole = new UserRole();
        //根据角色编码查到角色，刚注册有默认角色
        AuthRole role = authRoleService.getRoleByCode(AuthRoleConstant.ROLE_LV0);
        userRole.setUserId(id);
        userRole.setRoleId(role.getId());
        //插入t_auth_user_role表
        userRoleService.addUserRole(userRole);
    }
}
